//初始化
equations = [];
full_data = {};
exam_list = [];
now_exam_id = 0;
showPopup("加载数据中...");

const modal = document.querySelector('.modal');
const showModal = () => modal.style.display = 'flex';
const hideModal = () => modal.style.display = 'none';

function display_equations() {
    document.querySelector("#tips_area").innerHTML = `
        <div class="tips_text">若有小数，四舍五入至多保留两位小数</div>
    `;

    list = document.querySelector("#problem_list ul");
    list.innerHTML = "";
    for (var i = 0; i < equations.length; i++) {
        list.innerHTML += `
                <li class="problem_item" id="problem_item">
                    <p class="tips_text">题号:${i + 1}</p><span><p class="tips_text" style="color:rgba(234,0,0,0.7); display:none;" id="standard_answer" index=${i}>参考答案：10.00</p></span>
                    <p class="tips_text" id="equation" style="font-weight:bold;">题目描述</p>
                    <p class="equation center_text" id="equation">${format_equation(equations[i].equation)}</p>
                    <input type="text" id="answer_input" index=${i} class="input_box" placeholder="在此处输入">
                </li>
        `
    }
    if (equations.length == 0) {
        document.querySelector("#tips_area").innerHTML = `
        <div class="tips_text">没有任何题目数据</div>
        `;
    }
}

function display_wrong_equtions() {
    list = document.querySelector("#problem_list ul");
    list.innerHTML = "";
    for (var i = 0; i < equations.length; i++) {
        list.innerHTML += `
                <li class="problem_item" id="problem_item">
                    <p class="tips_text" id="equation" style="font-weight:bold;">题目描述</p><span><p class="tips_text" style="color:rgba(234,0,0,0.7); display:none;" id="standard_answer" index=${i}>参考答案：10.00</p></span>
                    <p class="equation center_text" id="equation">${format_equation(equations[i].equation)}</p>
                    <input type="text" id="answer_input" index=${i} class="input_box" placeholder="在此处输入">
                </li>
        `
    }
    document.querySelector("#problem_list").innerHTML += `
        <button class="blue_button" style="width: 20%; height: 40px; margin: 10px 40px; font-size: 26px;"
        onclick="display_prev_wrong_page()">上一页</button>
        <button class="blue_button" style="width: 20%; height: 40px; margin: 10px 40px; font-size: 26px;"
        onclick="display_next_wrong_page()">下一页</button>
    `;
}

function format_equation(equation) {
    let value = "";
    last = "";
    for (item of equation) {
        if (item != 'x' || last != '*') {
            value += last;
        }
        last = item;
    }
    value += item;
    return value;
}

async function check_answer() {
    freeArea = document.querySelector("#free_area");
    freeArea.innerHTML = `
        <button class="floating-button floating-button-right" onclick="exit_exam()">返回列表</button>
        <button class="floating-button floating-button-right" onclick="display_answer()" style="bottom:80px;">公布答案</button>
    `;

    answer_input_list = document.querySelectorAll("#answer_input");
    console.log(`即将对${equations.length}道题进行校验...`);
    console.log(equations);
    for (var i = 0; i < answer_input_list.length; i++) {
        // var index = answer_input_list[i].getAttribute("index");
        var index = i;
        equations[index]["uans"] = answer_input_list[i].value;
    }
    data = {
        id: now_exam_id,
        uid: getCookieValue("uid"),
        equations: equations
    };
    api = baseUrl + "/problem/judge";
    await fetch(api, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: getCookieValue("uid")
        },
        body: JSON.stringify(data)
    }).then(response => {
        console.log(response);
        return response.json();
    })
        .then(data => {
            console.log("校验结果：");
            console.log(data);
            array = data["data"]["equationExamVOS"];
            //补充参考答案
            AC_list = [];

            currectNumber = 0;
            incurrectNumber = 0;
            currectRate = 0;
            problems = document.querySelectorAll("#standard_answer");
            for (var i = 0; i < array.length; i++) {
                // var index = problems[i].getAttribute("index");
                var index = i;
                problems[i].innerHTML = `
                    参考答案：${array[index]["ans"]}
                `
                if ((array[index]["isCorrect"] ?? 0) == 1) {
                    AC_list.push(true);
                    currectNumber++;
                } else {
                    AC_list.push(false);
                    incurrectNumber++;
                }
            }
            var currectRate = (currectNumber / AC_list.length) * 100;
            currectRate = currectRate.toFixed(2) + "%";

            items = document.querySelectorAll("#problem_item");
            for (var i = 0; i < items.length; ++i) {
                if (AC_list[i]) {
                    items[i].classList.add("right_item");
                } else {
                    items[i].classList.add("wrong_item");
                }
            }

            table = document.querySelector("#modal_content");
            table.innerHTML = `
                <div class="rectangle_white info_rect">
                    <div class="center_title">测验结果</div>
                    <div style=" margin-top:20px;">
                        <div class="tips_text center_text">总题数: ${AC_list.length}</div>
                        <div class="tips_text center_text">正确题数: ${currectNumber}</div>
                        <div class="tips_text center_text">错误题数: ${incurrectNumber}</div>
                        <div class="tips_text center_text">正确率: ${currectRate}</div>
                    </div>
                    <button class="blue_button" onclick="hideModal()">关闭</button>
                </div>
            `;
            showModal();

        }).catch(error => {
            console.error(error);
        })
}

function display_answer() {
    freeArea = document.querySelector("#free_area");
    freeArea.innerHTML = `
        <button class="floating-button floating-button-right" onclick="exit_exam()">返回列表</button>
    `;
    standard_answers = document.querySelectorAll("#standard_answer");
    for (item of standard_answers) {
        item.style["display"] = "block";
    }
}

function log_out() {
    deleteCookie("uid");
    window.location.href = "../index.html";
}

function test() {
    api = baseUrl + "/problem/start-exam?eid=98";
    fetch(api, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            Authorization: getCookieValue("uid"),
        },
    }).then(response => response.json())
        .then(data => {
            console.log(data);
        }).catch(error => {
            console.error(error);
        })
}
now_page = 1;
page_size = 8;
display_now_page();

function enter_exam(id) {
    now_exam_id = id;

    this_title = "本测试没有标题";
    for (item of exam_list) {
        if (item.id == id) {
            this_title = item.title;
        }
    }
    document.querySelector("#problem_list #exam_title").innerHTML = this_title;

    document.querySelector("#exam_list_area").style["display"] = "none";
    document.querySelector("#problem_list_area").style["display"] = "block";
    freeArea = document.querySelector("#free_area");
    freeArea.innerHTML = `
        <button class="floating-button floating-button-right" onclick="exit_exam()">返回列表</button>
        <button class="floating-button floating-button-right" onclick="check_answer()" style="bottom:80px;">提交答案</button>
        <button class="floating-button floating-button-right" onclick="display_answer()" style="bottom:140px; display:none;">公布答案</button>
        
    `;

    api = baseUrl + `/problem/start-exam?eid=${id}`;
    fetch(api, {
        method: "GET",
        headers: {
            Authorization: getCookieValue("uid"),
            "Content-Type": "application/json"
        }
    }).then(response => response.json()).then(data => {
        console.log(data);
        if (data['code'] != 200) {
            // if (data["msg"] == "您已经完成该场次了") {
            //     exit_exam();
            //     showPopup("您已经完成该场次了");
            //     return;
            // }
            // if (data["msg"] == "比赛未开始") {
            //     exit_exam();
            //     showPopup("测验未开始");
            //     return;
            // }
            exit_exam();
            showPopup(data["msg"]);
            return;
        } else {
            equations = data['data'];
            display_equations();
        }
    }).catch(error => {
        console.error(error);
    })

}
function exit_exam() {
    document.querySelector("#exam_list_area").style["display"] = "block";
    document.querySelector("#problem_list_area").style["display"] = "none";
    document.querySelector("#free_area").innerHTML = "";
    display_now_page();
}
function cancel_register_exam(id) {
    showPopup("暂未完工呢");
}

function isExpired(endTime) {
    var currentTime = new Date();  // 当前时间
    var endDateTime = new Date(endTime);  // 结束时间

    if (endDateTime < currentTime) {
        return true;  // 结束时间早于当前时间
    } else {
        return false; // 结束时间晚于或等于当前时间
    }
}
function downloadData(url) {
    var link = document.createElement('a');
    link.href = url;
    link.download = '';
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}


function download_exam(exam_id, title) {
    api = baseUrl + `/problem/download?examId=${exam_id}`;
    fetch(api, {
        method: "GET",
        headers: {
            Authorization: getCookieValue("uid"),
        }
    }).then(response => response.blob())
        .then(blob => {
            // 创建一个临时链接来下载文件
            var downloadLink = document.createElement('a');
            downloadLink.href = URL.createObjectURL(blob);
            downloadLink.download = `${title}.xlsx`;
            // 触发下载
            downloadLink.click();
            // 释放 URL 对象
            URL.revokeObjectURL(downloadLink.href);
        })
        .catch(error => {
            console.error('下载文件时出现错误:', error);
        });
}

function display_now_page() {
    // return;
    api = baseUrl + `/problem/get-exam-list?pageNum=${now_page}&pageSize=${page_size}&classId=0`;
    fetch(api, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            Authorization: getCookieValue("uid"),
        },
    }).then(response => response.json())
        .then(data => {
            console.log(data);
            if (data["code"] != 200) {
                console.error(`获取测验列表出现错误, code=${data['code']}, msg=\"${data["msg"]}\"`);
                return;
            }
            list = data['data'];
            if (list.length == 0 && now_page > 1) {
                display_prev_page();
                return;
            }
            exam_list = list;
            table = document.querySelector("#exam_list ul");
            table.innerHTML = "";

            for (item of list) {
                if_start = ((item.ifStart ?? 0) != 0) ? true : false;
                if_signup = item.isSignup ?? 0;
                end_time = item.endTime;
                button1 = "";
                button2 = "";
                if (if_start) {
                    if (if_signup) {
                        button1 = `<button class="useful" onclick="enter_exam(${item.id})">进入测验</button>`;
                        button2 = `<button class="useless">取消报名</button>`;
                    } else {
                        button1 = `<button class="useless">已开始</button>`;
                        button2 = `<button class="useless">取消报名</button>`;
                    }
                } else {
                    if (if_signup) {
                        button1 = `<button class="useless">进入测验</button>`;
                        button2 = `<button class="useful" onclick="cancel_register_exam(${item.id})">取消报名</button>`;
                    } else {
                        button1 = `<button class="useful" onclick="register_exam(${item.id})">报名</button>`;
                        button2 = `<button class="useless">取消报名</button>`;
                    }
                }
                button3 = "";
                if (isExpired(end_time)) {
                    button3 = `<button class="useful" onclick="download_exam(${item.id}, '${item.title}')">导出题目</button>`;
                } else {
                    button3 = `<button class="useless">导出题目</button>`;
                }
                table.innerHTML += `
                <li>
                    <div style="width: 88%;">
                        <p class="title">${item.title ?? "没有标题的测验"}</p>
                        <p style="white-space: pre;" class="description">${item.description ?? "没有描述的测验"}</p>
                    </div>
                    <div style="width: 10%; display:inline-block; margin: 55px 20px;">
                        ${button1}
                        ${button2}
                        ${button3}
                    </div>
                </li>
                `
            }
        }).catch(error => {
            console.error(error);
        })
}
function display_prev_page() {
    if (now_page > 1) {
        now_page--;
        display_now_page();
    }
}
function display_next_page() {
    now_page++;
    display_now_page();
}

function create_exam_request() {
    api = baseUrl + `/problem/create-exam`;
    var titleInput = document.getElementById('title_input').value;
    var descriptionInput = document.getElementById('description_input').value;
    var startTimeInput = document.getElementById('start_time_input').value;
    var endTimeInput = document.getElementById('end_time_input').value;
    var gradeSelector = document.getElementById('grade_selector').value;
    var problemNumber = document.getElementById('problem_number').value;

    if (!problemNumber) {
        showPopup("题目数量不可为空");
        return;
    }
    if (problemNumber < 1 || problemNumber > 50) {
        showPopup("题目数量应在1到50之间");
        return;
    }
    if (!isValidTime(startTimeInput)) {
        showPopup("开始时间不合法");
        return;
    }
    if (!isValidTime(endTimeInput)) {
        showPopup("结束时间不合法");
        return;
    }
    data = {
        title: titleInput,
        description: descriptionInput,
        startTime: convertDataToISOString(startTimeInput),
        endTime: convertDataToISOString(endTimeInput),
        level: gradeSelector,
        num: problemNumber
    };
    showPopup("创建中...请稍等...");
    fetch(api, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Authorization: getCookieValue("uid"),
        },
        body: JSON.stringify(data),
    }).then(response => response.json()).then(data => {
        console.log(data);
        if (data["code"] != 200) {
            console.error(data["code"] + " " + data["msg"]);
            showPopup("出错了");
        } else {
            hideModal();
            showPopup("创建成功");
            display_now_page();
        }
    }).catch(error => {
        console.error(error);
        showPopup("出错了");
    })
}

function register_exam(id) {
    api = baseUrl + `//problem/signup?eid=${id}`;
    fetch(api, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            Authorization: getCookieValue("uid"),
        },
    }).then(response => response.json())
        .then(data => {
            console.log(data);
            if (data['code'] == 200) {
                showPopup("报名成功");
                display_now_page();
            } else {
                showPopup("报名出现异常");
            }
        }).catch(error => {
            console.error(error);
        })
}

function create_exam() {
    showModal();
    table = document.querySelector("#modal_content");
    table.innerHTML = `
            <div id="info_input_area">
                <div class="rectangle_white info_rect">
                    <div class="center_title small_text">请输入测验标题</div>
                    <input type="text" class="input_box center_text" id="title_input">
                    <div class="center_title small_text">补充对本测验的描述</div>
                    <textarea type="text" id="description_input" class="input_box" style="height:100px; min-width: 500px; max-width:800px; padding:6px;"></textarea>
                    <div class="center_title small_text">请设置测验开始时间</div>
                    <input type="text" class="input_box center_text" id="start_time_input" value="${getTimeWithOffset(120)}">
                    <div class="center_title small_text">请设置测验结束时间</div>
                    <input type="text" class="input_box center_text" id="end_time_input" value="${getTimeWithOffset(3720)}">
                    <div class="center_title small_text">请设置练习难度</div>
                    <select name="grade_selector" id="grade_selector" class="grade_selector">
                        <option value="1">一年级</option>
                        <option value="2">二年级</option>
                        <option value="3">三年级</option>
                        <option value="4">四年级</option>
                        <option value="5">五年级</option>
                        <option value="6">六年级</option>
                    </select>
                    <input class="input_box" id="problem_number" type="number" placeholder="题目数量（1~50）">
                    <button class="blue_button" onclick="create_exam_request()">创建测验</button>
                    <button class="blue_button" onclick="hideModal()">取消</button>
                </div>
            </div>
    `;
}
wrong_page_size = 50;
wrong_now_page = 1;

function display_prev_wrong_page() {
    if (wrong_now_page > 1) {
        wrong_now_page--;
        display_wrong_history();
    }
}
function display_next_wrong_page() {
    wrong_now_page++;
    display_wrong_history();
}

function display_wrong_history() {

    document.querySelector("#problem_list").innerHTML = `
        <div class="head_title center_text" id="exam_title"></div>
        <div class="center_text" id="tips_area"></div>
        <ul>
        </ul>
    `;

    api = baseUrl + `/wrong/select-page?pageSize=${wrong_page_size}&pageNum=${wrong_now_page}`;
    document.querySelector("#exam_list_area").style["display"] = "none";
    document.querySelector("#problem_list_area").style["display"] = "block";
    document.querySelector("#problem_list #exam_title").innerHTML = "";
    freeArea = document.querySelector("#free_area");
    freeArea.innerHTML = `
        <button class="floating-button floating-button-right" onclick="exit_exam()">返回列表</button>
        <button class="floating-button floating-button-right" onclick="check_answer()" style="bottom:80px;">提交本页</button>
    `;

    fetch(api, {
        method: "GET",
        headers: {
            Authorization: getCookieValue("uid")
        }
    }).then(response => response.json())
        .then(data => {
            console.log(data);
            if (data['code'] != 200) {
                showPopup("似乎出了点问题");
            } else {
                equations = data['data'];
                if (equations.length == 0 && wrong_now_page > 1) {
                    display_prev_wrong_page();
                    return;
                }
                display_wrong_equtions();
            }

        }).catch(error => {
            console.error(error);
        })


}

function display_info() {
    document.querySelector("#exam_list_area").style["display"] = "none";
    document.querySelector("#problem_list_area").style["display"] = "none";
    document.querySelector("#problem_list #exam_title").innerHTML = "";
    freeArea = document.querySelector("#free_area");
    const api = baseUrl + `/wrong/get-problem-log`;

    fetch(api, {
        method: "GET",
        headers: {
            Authorization: getCookieValue("uid")
        }
    }).then(response => response.json())
        .then(data => {
            /*data数据形如：
            {
              "code": 0,
              "data": {
                "monthCorrectNum": 0,
                "monthCorrectRate": 0,
                "monthNum": 0,
                "weekCorrectNum": 0,
                "weekCorrectRate": 0,
                "weekNum": 0
              },
              "msg": "string"
            }
            */

            const { monthCorrectNum, monthCorrectRate, monthNum, weekCorrectNum, weekCorrectRate, weekNum } = data.data;

            // 创建显示元素的容器
            const container = document.createElement('div');
            container.className = 'statistics-container';

            // 创建月份统计元素
            const monthStats = document.createElement('div');
            monthStats.className = 'stats';
            monthStats.innerHTML = `
      <h3>月统计</h3>
      <p>做题数: ${monthNum}</p>
      <p>正确数: ${monthCorrectNum}</p>
      <p>正确率: ${monthCorrectRate.toFixed(2)}%</p>
    `;

            // 创建周统计元素
            const weekStats = document.createElement('div');
            weekStats.className = 'stats';
            weekStats.innerHTML = `
      <h3>周统计</h3>
      <p>做题数: ${weekNum}</p>
      <p>正确数: ${weekCorrectNum}</p>
      <p>正确率: ${weekCorrectRate.toFixed(2)}%</p>
    `;

            // 将统计元素添加到容器中
            container.appendChild(monthStats);
            container.appendChild(weekStats);

            // 将容器添加到页面中
            freeArea.innerHTML = '';
            freeArea.appendChild(container);

            // 创建返回按钮
            const backButton = document.createElement('button');
            backButton.className = 'floating-button floating-button-right';
            backButton.textContent = '返回列表';
            backButton.addEventListener('click', exit_exam);

            // 将返回按钮添加到页面中
            freeArea.appendChild(backButton);
        })
        .catch(error => {
            console.error(error);
        });


}